package com.xiaoshuidi.cloud.module.member.repository;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xiaoshuidi.cloud.module.member.controller.app.questionnaireinfo.vo.ParticipateVO;
import com.xiaoshuidi.cloud.module.member.mapper.questionnaireinfo.MemberAnswerMapper;
import com.xiaoshuidi.cloud.module.member.pojo.questionnaireinfo.MemberAnswer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
@RequiredArgsConstructor
@Slf4j
public class MemberAnswerRepository extends ServiceImpl<MemberAnswerMapper, MemberAnswer> {
    private final MemberAnswerMapper mapper;

    public Boolean participateOrNot(ParticipateVO participateVO) {
        LambdaQueryWrapperX<MemberAnswer> wrapper = new LambdaQueryWrapperX<MemberAnswer>()
                .eqIfPresent(MemberAnswer::getCreator, participateVO.getUserId())
                .eqIfPresent(MemberAnswer::getQuestionnaireId, participateVO.getId());
        List<MemberAnswer> list = mapper.selectList(wrapper);
        if (list != null && list.size() > 0) {
            return true;
        }
        return false;
    }

    public void updateUserId(Long oldUserId, Long userId) {
        LambdaQueryWrapperX<MemberAnswer> wrapper = new LambdaQueryWrapperX<MemberAnswer>()
                .eqIfPresent(MemberAnswer::getCreator, oldUserId);
        List<MemberAnswer> list = mapper.selectList(wrapper);

        if (list != null && list.size() > 0) {
            List<Long> questionnairedIds = list.stream().map(MemberAnswer::getQuestionnaireId).collect(Collectors.toList());
            LambdaQueryWrapperX<MemberAnswer> wr = new LambdaQueryWrapperX<MemberAnswer>()
                    .eqIfPresent(MemberAnswer::getCreator, userId);
            List<MemberAnswer> list2 = mapper.selectList(wr);
            if (list2!=null&&list2.size()>0) {
                List<Long> collect = list2.stream().map(MemberAnswer::getQuestionnaireId).collect(Collectors.toList());
                List<Long> containsCollect = questionnairedIds.stream().filter(o -> collect.contains(o)).collect(Collectors.toList());
                List<Long> notContainsCollect = questionnairedIds.stream().filter(o -> !collect.contains(o)).collect(Collectors.toList());

                //list2里包含的全部删除
                mapper.deleteByQuestionnairedId(containsCollect, oldUserId);
                //list2里不包含的全部替换
                mapper.updateUserId(oldUserId, userId, notContainsCollect);
            }else {
                //list2里不包含的全部替换
                mapper.updateUserId(oldUserId, userId, questionnairedIds);
            }
        }

    }
}
